<template>
  <s-layout
    title="家庭"
    navbar="inner"
    tabbar="/pages/message/family"
    color="#000000"
    :onShareAppMessage="true"
    :leftIcon="''"
    :bgStyle="pageStyle.background"
    :navbarStyle="template.style?.navbar"
    :showFloatButton="true"
    :showLeftHome="false"
    showAddIcon
    main-background="#F5F5F5"
    @openLoginPopup="openLoginPopup"
  >
    <view v-show="false">{{ list }}</view>
    <scroll-view scroll-y="true"
                 :style="{
                    height: `calc(100vh - ${scrollView_height}px)`
                 }"
                 @scroll="genealogyScroll"
    >
      <view class="genealogy flex flex-column align-center">
        <!-- 未登录 -->
        <view v-if="familyList.length == 0"
              class="genealogy_bg wh_702 hW_636 mt_16 flex"
              style="border-radius: 21rpx;overflow:hidden;position: relative;"
              @click.stop="goToPath()"
        >
          <view
            style="position: absolute;background: rgba(255,255,255,0.5);width: 100%;height: 100%;backdrop-filter: blur(15rpx);"></view>
          <view class="flex flex-column align-center flex-sub"
                style="position: absolute;width: 100%;height: 100%;z-index: 10">
            <view class="z_1 mt_20 flex justify-between"
                  style="width: 100%;"
            >
              <view class="flex flex-column ml_24">
                <view class="fs_38 color_292929 fw_500">{{ '我的家庭' }}</view>
                <view class="fs_22 fw_400 color_292929 mt_15">家庭号: {{ '66666GT' }}</view>
                <view class="fs_22 fw_400 color_292929 mt_11">发起人: {{ '未登录' }}</view>
                <view class="fs_22 fw_400 color_292929 mt_11">
                  创建时间：{{ dayjs(new Date().getTime()).format('YYYY年MM月DD日') }}
                </view>
              </view>
              <view class="flex flex-column align-end mr_24">
                <view class="flex align-center">
                  <!-- #ifndef H5 -->
                  <view class="wh_100 hW_49 fs_25 fw_500 flex align-center justify-center"
                        style="background: rgba(255,255,255,0.8);border-radius: 13rpx;color: #000000;"
                        @click.stop="sweep"
                  >
                    扫一扫
                  </view>
                  <!-- #endif -->
                  <view class="wh_54 hW_49 flex align-center justify-center ml_30"
                        style="border-radius: 13rpx;background: rgba(255,255,255,0.8)"
                        @click.stop="administration(item,true)"
                  >
                    <image :src="`${IMG_URL}/genealogy/genealogy_code.png`"
                           class="wh_31 hW_31"
                    ></image>
                  </view>
                </view>
                <view class="fs_34 fw_500 color_292929 mt_38" @click.stop="administration(item)">
                  设置
                </view>
              </view>
            </view>
            <view style="width: 100%;" class="ml_50 mt_15">
              <view class="wh_179 hW_58 z_10 fs_34 fw_bold flex align-center justify-center"
                    style="background: rgba(255,255,255,0.6);border-radius: 29rpx;color: #66483D;position: absolute;left: 50%;transform: translateX(-50%);bottom: 55rpx"
              >
                进入家庭
              </view>
            </view>
            <view class="flex align-center"
                  style="position: absolute;left: 50%;transform: translateX(-50%);bottom: 22rpx;white-space: nowrap"
            >
              <view class="fs_24 fw_500 mr_16 color_292929">
                照片: {{ 10 }}张
              </view>
              <view class="fs_24 fw_500 mr_16 color_292929">
                圈子: {{ 10 }}条
              </view>
              <view class="fs_24 fw_500 mr_16 color_292929">
                生日: {{ 10 }}人
              </view>
              <view class="fs_24 fw_500 color_292929">
                纪念日: {{ 10 }}个
              </view>
            </view>
          </view>
          <view style="position: absolute;z-index:2;width: 100%;height: 100%">
            <image :src="`${IMG_URL}/family/family_background.png`"
                   class="wh_498 hW_318"
                   style="position: absolute;border-radius: 20rpx;overflow: hidden;left: 50%;transform: translateX(-50%);bottom: 122rpx;"
            ></image>
          </view>
        </view>
        <!-- 只有一个家庭 -->
        <view v-else-if="familyList.length === 1">
          <view class="genealogy_bg wh_702 hW_636 mt_16 flex"
                style="border-radius: 21rpx;overflow:hidden;position: relative;"
                v-for="(item,index) in familyList" :key="index"
                :style="setBackground(index)"
                @click.stop="goToPath(item)"
          >
            <view
              style="position: absolute;background: rgba(255,255,255,0.5);width: 100%;height: 100%;backdrop-filter: blur(15rpx);"></view>
            <view class="flex flex-column align-center flex-sub"
                  style="position: absolute;width: 100%;height: 100%;z-index: 10">
              <view class="z_1 mt_20 flex justify-between"
                    style="width: 100%;"
              >
                <view class="flex flex-column ml_24">
                  <view class="fs_38 color_292929 fw_500">{{ item.name }}</view>
                  <view class="fs_22 fw_400 color_292929 mt_15">家庭号: {{ item.family_id }}</view>
                  <view class="fs_22 fw_400 color_292929 mt_11">发起人: {{ item.create_user_name }}</view>
                  <view class="fs_22 fw_400 color_292929 mt_11">
                    创建时间：{{ dayjs(item.createtime * 1000).format('YYYY年MM月DD日') }}
                  </view>
                </view>
                <view class="flex flex-column align-end mr_24">
                  <view class="flex align-center">
                    <!-- #ifndef H5 -->
                    <view class="wh_100 hW_49 fs_25 fw_500 flex align-center justify-center"
                          style="background: rgba(255,255,255,0.8);border-radius: 13rpx;color: #000000;"
                          @click.stop="sweep"
                    >
                      扫一扫
                    </view>
                    <!-- #endif -->
                    <view class="wh_54 hW_49 flex align-center justify-center ml_30"
                          style="border-radius: 13rpx;background: rgba(255,255,255,0.8)"
                          @click.stop="administration(item,true)"
                    >
                      <image :src="`${IMG_URL}/genealogy/genealogy_code.png`"
                             class="wh_31 hW_31"
                      ></image>
                    </view>
                  </view>
                  <view class="fs_34 fw_500 color_292929 mt_38" @click.stop="administration(item)">
                    设置
                  </view>
                </view>
              </view>
              <view style="width: 100%;" class="ml_50 mt_15">
                <view class="wh_179 hW_58 z_10 fs_34 fw_bold flex align-center justify-center"
                      style="background: rgba(255,255,255,0.6);border-radius: 29rpx;color: #66483D;position: absolute;left: 50%;transform: translateX(-50%);bottom: 55rpx"
                >
                  进入家庭
                </view>
              </view>
              <view class="flex align-center"
                    style="position: absolute;left: 50%;transform: translateX(-50%);bottom: 22rpx;white-space: nowrap"
              >
                <view class="fs_24 fw_500 mr_16 color_292929">
                  照片: {{ item.images_count }}张
                </view>
                <view class="fs_24 fw_500 mr_16 color_292929">
                  圈子: {{ item.circle_count }}条
                </view>
                <view class="fs_24 fw_500 mr_16 color_292929">
                  生日: {{ item.memory_birthday_count }}人
                </view>
                <view class="fs_24 fw_500 color_292929">
                  纪念日: {{ item.memory_memory_count }}个
                </view>
              </view>
            </view>
            <view style="position: absolute;z-index:2;width: 100%;height: 100%">
              <image :src="`${IMG_URL}/family/family_background.png`"
                     v-if="item.cover_lsit.length <= 0"
                     class="wh_498 hW_318"
                     style="position: absolute;border-radius: 20rpx;overflow: hidden;left: 50%;transform: translateX(-50%);bottom: 122rpx;"
              ></image>
              <swiper class="wh_498 hW_318"
                      v-else
                      style="position: absolute;border-radius: 20rpx;overflow: hidden;left: 50%;transform: translateX(-50%);bottom: 122rpx;"
                      autoplay
                      circular
                      indicator-color="rgba(255,255,255,0.1)"
                      indicator-active-color="#fff"
                      :interval="3000"
                      :duration="500"
                      @change="urlChange($event,index)"
              >
                <block v-for="(item,index) in item.cover_lsit" :key="index">
                  <swiper-item>
                    <navigator :url="item.url">
                      <image :src="item" class="wh_508 hW_328" mode="aspectFill" />
                    </navigator>
                  </swiper-item>
                </block>
              </swiper>
            </view>
          </view>
        </view>
        <!-- 拥有多个家庭 -->
        <view v-else>
          <view class="genealogy_bg wh_702 hW_374 mt_16 flex"
                style="border-radius: 21rpx;overflow:hidden;position: relative;"
                v-for="(item,index) in familyList" :key="index"
                :style="setBackground(index)"
                @click.stop="goToPath(item)"
                @touchstart="longpress"
                @touchend="touchend"
          >
            <view
              style="position: absolute;background: rgba(255,255,255,0.5);width: 100%;height: 100%;backdrop-filter: blur(15rpx);"></view>
            <view class="flex flex-column align-center flex-sub" style="position: absolute;width: 100%;height: 100%;">
              <view class="z_1 mt_30 flex justify-between"
                    style="width: 100%;"
              >
                <view class="flex flex-column ml_24">
                  <view class="fs_38 color_292929 fw_500">{{ item.name }}</view>
                  <view class="fs_22 fw_400 color_292929 mt_15">家庭号: {{ item.family_id }}</view>
                  <view class="fs_22 fw_400 color_292929 mt_15">发起人: {{ item.create_user_name }}</view>
                  <view class="fs_22 fw_400 color_292929 mt_15">
                    创建时间：{{ dayjs(item.createtime * 1000).format('YYYY年MM月DD日') }}
                  </view>
                </view>
                <view class="flex flex-column align-end mr_24">
                  <view class="flex align-center">
                    <!-- #ifndef H5 -->
                    <view class="wh_100 hW_49 fs_25 fw_500 flex align-center justify-center"
                          style="background: rgba(255,255,255,0.8);border-radius: 13rpx;color: #000000;"
                          @click.stop="sweep"
                    >
                      扫一扫
                    </view>
                    <!-- #endif -->
                    <view class="wh_54 hW_49 flex align-center justify-center ml_30"
                          style="border-radius: 13rpx;background: rgba(255,255,255,0.8)"
                          @click.stop="administration(item,true)"
                    >
                      <image :src="`${IMG_URL}/genealogy/genealogy_code.png`"
                             class="wh_31 hW_31"
                      ></image>
                    </view>
                  </view>
                  <view class="fs_34 fw_500 color_292929 mt_38" @click.stop="administration(item)">
                    设置
                  </view>
                </view>
              </view>
              <view style="width: 100%;" class="ml_50 mt_15">
                <view class="wh_145 hW_49 z_10 fs_28 fw_500 flex align-center justify-center"
                      style="background: rgba(255,255,255,0.6);border-radius: 29rpx;color: #66483D;"
                >
                  进入家庭
                </view>
              </view>
              <view class="flex align-center"
                    style="position: absolute;left: 24rpx;bottom: 22rpx"
              >
                <view class="fs_24 fw_500 mr_16 color_292929">
                  照片: {{ item.images_count }}张
                </view>
                <view class="fs_24 fw_500 mr_16 color_292929">
                  圈子: {{ item.circle_count }}条
                </view>
                <view class="fs_24 fw_500 mr_16 color_292929">
                  生日: {{ item.memory_birthday_count }}人
                </view>
                <view class="fs_24 fw_500 color_292929">
                  纪念日: {{ item.memory_memory_count }}个
                </view>
              </view>
            </view>
            <view style="position: absolute;z-index:2">
              <image :src="`${IMG_URL}/family/family_background.png`"
                     v-if="item.cover_lsit.length <= 0"
                     class="wh_280 hW_186"
                     style="position: absolute;top: 97rpx;left: 321rpx;border-radius: 20rpx;overflow: hidden;z-index:-1"
              ></image>
              <swiper class="wh_280 hW_186"
                      v-else
                      style="position: absolute;top: 97rpx;left: 321rpx;border-radius: 20rpx;overflow: hidden;"
                      autoplay
                      circular
                      indicator-color="rgba(255,255,255,0.1)"
                      indicator-active-color="#fff"
                      :interval="3000"
                      :duration="500"
                      @change="urlChange($event,index)"
              >
                <block v-for="(item,index) in item.cover_lsit" :key="index">
                  <swiper-item>
                    <navigator :url="item.url">
                      <image :src="item" class="wh_290 hW_196" mode="aspectFill" />
                    </navigator>
                  </swiper-item>
                </block>
              </swiper>
            </view>
          </view>
        </view>
        <view class="flex align-center fs_22 fw_500 color_696969 mt_40 mb_40">
          <view class="mr_30" @click.stop="openFamilyPopup">新建家庭</view>
          <view class="ml_30" @click.stop="openAddFamilyPopup">加入家庭</view>
        </view>
      </view>
    </scroll-view>

    <s-login-popup ref="loginPopup" @confirm="loginConfirm" @openPopup="openPopup"></s-login-popup>
  </s-layout>
</template>

<script setup>
  // 隐藏原生tabBar
  uni.hideTabBar({
    fail: () => {
    },
  });

  import sheep from '@/sheep';
  import { computed, reactive, onMounted, ref } from 'vue';
  import dayjs from 'dayjs';
  import { onShow } from '@dcloudio/uni-app';

  const pageStyle = reactive({
    background: { color: '#F5F5F5', src: '' },
  });
  const template = computed(() => sheep.$store('app').template.user);
  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);
  const familyList = ref();
  const isLogin = computed(() => sheep.$store('user').isLogin);
  const loginPopup = ref();
  // 家庭列表
  const list = computed(() => {
    let arr = sheep.$store('family').list;
    arr.forEach((item) => {
      item.urlIndex = 0;
    });
    familyList.value = arr;
    return arr;
  });

  const setBackground = (index) => {
    // if (familyList.value[index].cover_lsit.length <= 0) {
    return {
      background: `url(${IMG_URL}/family/family_background.png) no-repeat`,
    };
    // }
    // return {
    //   background: `url(${familyList.value[index].cover_lsit[familyList.value[index].urlIndex]})  no-repeat`,
    //   'background-size': '100%',
    // };
  };

  const urlChange = (e, index) => {
    familyList.value[index].urlIndex = e.detail.current;
  };

  const scrollView_height = computed(() => {
    let height = 0;
    height = Number(sheep.$platform.device.statusBarHeight) + Number(sheep.$store('system_info').tabbar_height) + 44;
    return height;
  });

  const state = reactive({
    list: [
      {
        name: '中华姓氏',
      },
      {
        name: '寻根拜祖',
      },
      {
        name: '老黄历',
      },
      {
        name: '今日运势',
      },
    ],
    // 是否长按
    isLongPress: false,
    // 长按时间
    longpress_time: null,
    // 是否打开弹窗
    is_open: false,
  });

  uni.$on('openLoginPopup', () => {
    loginPopup._value.openPopup();
  });
  function openLoginPopup(){
    loginPopup._value.openPopup();
  }
  uni.$on('closeLoginPopup', () => {
    if (state.is_open) {
      loginPopup._value.closePopup();
      state.is_open = false;
    }
  });

  function openPopup() {
    state.is_open = true;
  }

  onShow(async () => {
    if (!!isLogin.value) {
      await sheep.$store('family').getList();
      await sheep.$store('family').getFamilyTree();
      await sheep.$store('family').getFamilyRemindList();
    }
  });

  function goToPath(info = {}) {
    if (!isLogin.value) {
      loginPopup._value.openPopup();
      return;
    }
    sheep.$router.go('/pages/family/familyDetails', {
      family_id: info.id,
      code: info.family_id,
      is_own: info.is_owner,
    });
  }

  function administration(info = {}, is_flag = false) {
    if (!!state.isLongPress) {
      return;
    }
    if (!isLogin.value) {
      loginPopup._value.openPopup();
      return;
    }
    sheep.$router.go('/pages/familyPage/familyEdit', {
      family_id: info.id,
      code: info.family_id,
      is_own: info.is_my,
      is_flag: is_flag,
    });
  }

  function loginConfirm() {
    loginPopup._value.closePopup();
    // #ifdef MP-WEIXIN
    sheep.$router.go('/pages/login/wechat_login');
    // #endif
    // #ifndef MP-WEIXIN
    sheep.$router.go('/pages/login/phoneLogin');
    // #endif
  }

  // 加入家庭
  function openAddFamilyPopup() {
    if (!isLogin.value) {
      loginPopup._value.openPopup();
      return;
    }
    sheep.$router.go('/pages/familyPage/joinFamily');
  }

  function openFamilyPopup() {
    if (!isLogin.value) {
      loginPopup._value.openPopup();
      return;
    }
    sheep.$router.go('/pages/family/foundFamily');
  }

  // 长按进行排序
  function longpress() {
    if (!isLogin.value) {
      loginPopup._value.openPopup();
      return;
    }
    state.longpress_time = setTimeout(() => {
      sheep.$router.go('/pages/family/familyList');
    }, 2000);
    state.isLongPress = true;
  }

  // 滑动取消长按
  function genealogyScroll() {
    touchend();
  }

  // 取消长按
  function touchend() {
    clearTimeout(state.longpress_time);
    state.isLongPress = false;
  }

  function sweep() {
    // #ifdef APP-PLUS
    if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios') {
      uni.scanCode({
        success: (res) => {
          // showAuthModal('addFriend');
        },
      });
    } else {
      let res = plus.navigator.checkPermission('android.permission.CAMERA');
      if (res == 'authorized') {
        uni.scanCode({
          success: (res) => {
            console.log('获取到的信息=>', res);
            if (res.scanType == 'QR_CODE') {
              const result = res.result.split('?')[1];
              const qrcode = result.split('=')[1];
              uni.showModal({
                title: '授权登录',
                content: '是否授权登录',
                success: async (modal) => {
                  if (modal.confirm) {
                    const { code, msg } = await sheep.$api.user.userLogin({
                      qr_code: qrcode,
                      username: sheep.$store('user').userInfo.mobile,
                    });
                    if (code == 1) {
                      sheep.$helper.toast('授权成功');
                    } else {
                      sheep.$helper.toast(msg);
                    }
                  }
                },
              });
            }
          },
        });
      } else {
        uni.showModal({
          title: '开启相机权限',
          content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
          success: async (res) => {
            if (res.confirm) {
              if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios') {
                let limitsOfAuthority = await permision.judgeIosPermission('android.permission.CAMERA');
                if (limitsOfAuthority == 1) {
                  uni.scanCode({
                    success: (res) => {
                      // showAuthModal('addFriend');
                    },
                  });
                } else if (limitsOfAuthority == 0) {
                  uni.showModal({
                    title: '开启相机权限',
                    content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                    success: async (res) => {
                      if (res.confirm) {
                        permision.gotoAppPermissionSetting();
                      }
                    },
                  });
                } else {
                  uni.showModal({
                    title: '开启相机权限',
                    content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                    success: async (res) => {
                      if (res.confirm) {
                        permision.gotoAppPermissionSetting();
                      }
                    },
                  });
                }
              } else {
                let limitsOfAuthority = await permision.requestAndroidPermission('android.permission.CAMERA');
                if (limitsOfAuthority == 1) {
                  uni.scanCode({
                    success: (res) => {
                      // showAuthModal('addFriend');
                    },
                  });
                } else if (limitsOfAuthority == 0) {
                  uni.showModal({
                    title: '开启相机权限',
                    content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                    success: async (res) => {
                      if (res.confirm) {
                        permision.gotoAppPermissionSetting();
                      }
                    },
                  });
                } else {
                  uni.showModal({
                    title: '开启相机权限',
                    content: '你还没有开启相机权限，无法使用拾亲扫描功能、拍照或录制视频功能',
                    success: async (res) => {
                      if (res.confirm) {
                        permision.gotoAppPermissionSetting();
                      }
                    },
                  });
                }
              }
            }
          },
        });
      }
    }
    // #endif
    // #ifdef MP-WEIXIN
    uni.scanCode({
      success: async (res) => {
        console.log('获取到的信息=>', res);
        // showAuthModal('addFriend');
        if (res.scanType == 'QR_CODE') {
          const result = res.result.split('?')[1];
          const qrcode = result.split('=')[1];
          uni.showModal({
            title: '授权登录',
            content: '是否授权登录',
            success: async (modal) => {
              if (modal.confirm) {
                const { code, msg } = await sheep.$api.user.userLogin({
                  qr_code: qrcode,
                  username: sheep.$store('user').userInfo.mobile,
                });
                if (code == 1) {
                  sheep.$helper.toast('授权成功');
                } else {
                  sheep.$helper.toast(msg);
                }
              }
            },
          });
        }
      },
    });
    // #endif
  }
</script>


<style scoped lang="scss">
  .genealogy_bg {
    background: url($uni-bg-url-sq + '/family/family_background.png') no-repeat;
    background-size: 100% 100%;
    backdrop-filter: blur(2px);
  }

  .genealogy_content {
    background: url($uni-bg-url-sq + '/genealogy/genealogy_shu.png') 329rpx 110rpx no-repeat;
    background-size: 254rpx 213rpx;
    height: 100%;
  }
</style>
